package com.jing.weibo.controller.fansattention;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import weibo4j.model.WeiboException;

import com.jing.system.comm.BaseController;
import com.jing.system.comm.contants.SystemCons;
import com.jing.system.comm.contants.WeiboCons;
import com.jing.system.comm.enums.FansAttentionType;
import com.jing.system.utils.DateUtil;
import com.jing.system.utils.StringUtil;
import com.jing.system.utils.freeze.FreezeMpUserUtil;
import com.jing.system.utils.freeze.FreezeUserUtil;
import com.jing.weibo.pojo.fans.Fansattention;
import com.jing.weibo.pojo.pb.PbUserTypeSeat;
import com.jing.weibo.pojo.pb.PbUserTypeSeatLog;
import com.jing.weibo.pojo.user.UserInfo;
import com.jing.weibo.pojo.user.UserMp;
import com.jing.weibo.service.fans.FansAttentionService;
import com.jing.weibo.service.pb.PbUserTypeSeatLogService;
import com.jing.weibo.service.pb.PbUserTypeSeatService;
import com.jing.weibo.service.user.UserInfoService;
import com.jing.weibo.service.user.UserMpService;
import com.jing.weibo.ws.sina.FriendshipsService;
import com.jing.weibo.ws.sina.TimelineService;

/**
 * 用户关注和粉丝的Controller
 * @author jing.yue
 * @version 2012/08/29 1.0.0
 */
@Controller
public class FansAttentionController extends BaseController {

	private static final Logger logger = Logger.getLogger(FansAttentionController.class);

	@Autowired
	private TimelineService timelineService;
	@Autowired
	private FriendshipsService friendshipsService;
	@Autowired
	private UserInfoService userInfoService;
	@Autowired
	private UserMpService userMpService;
	@Autowired
	private FansAttentionService fansAttentionService;
	@Autowired
	private PbUserTypeSeatService pbUserTypeSeatService;
	@Autowired
	private PbUserTypeSeatLogService pbUserTypeSeatLogService;

	/**
	 * 参与互粉
	 * @return
	 */
	@RequestMapping(value = "/fansattention/json/joinMp")
	@ResponseBody
	public ModelMap joinMp(HttpServletRequest request, Integer joinMpPbType, String isSendWeibo) {
		String result = null;
		String unFreezeMsg = null;
		StringBuffer errorWeiboMsg = new StringBuffer();
		int addFansNum = 0;
		int addAttentionNum = 0;
		UserInfo userInfo = getSessionUser(request);
		String freezeResult = FreezeMpUserUtil.getMpFreezeUser(userInfo.getUsername());
		try {
			//判断互粉是否在解冻状态
			if(!SUCCESS.equals(freezeResult)) {
				result = ERROR_USER_FREEZE_MP;
				unFreezeMsg = String.format("您在%s分钟内互粉过了，请休息会吧~ 距离下次互粉还有%s分钟!{如果您想让等待时间更短，您可以通过升级来实现噢~}", userInfo.getFreezemptime(), freezeResult);
			}
			else if(userInfo.getIsopenmp().intValue() == 0) {
				result = ERROR_ISOPENMP;
			}
			else {
				//先同步信息
				synchrologInfo(request, FansAttentionType.TYPE_FANS);

				//根据用户名和类型获取参加了互粉的用户和在粉丝中不存在的前xxx个用户
				userInfo.setJoinmpnum(SystemCons.JOINMP_USERINFO_NUM);
				userInfo.setFatype(FansAttentionType.TYPE_FANS.getCode());
				userInfo.setPbtypeid(joinMpPbType);
				List<UserMp> userMps = userMpService.findByJoinMpPbTypeUserMp(userInfo);
				if(joinMpPbType.intValue() == 1) {
					List<UserMp> notPbTypeUsers = userMpService.findByNotPbTypeUserMp(userInfo, FreezeUserUtil.getFreezeUsers());
					userMps.addAll(notPbTypeUsers);
				}

				String following = "true";
				String followme = "true";
				for (UserMp um : userMps) {
					if(addFansNum >= WeiboCons.weibo_mp_max_num) {
						break;
					}
					try {
						//用户关注当前登录用户
						friendshipsService.createFriendshipsById(userInfo.getUsername(), um.getToken());
						addFansNum ++;

						try {
							//当前登录用户关注用户
							friendshipsService.createFriendshipsById(um.getUsername(), userInfo.getToken());

							//添加用户分区位置关注记录
							PbUserTypeSeat pbUserTypeSeat = new PbUserTypeSeat();
							pbUserTypeSeat.setUsername(um.getUsername());
							pbUserTypeSeat.setTypeid(joinMpPbType);
							pbUserTypeSeat = pbUserTypeSeatService.findByUsernameTypeidPuts(pbUserTypeSeat);
							if(pbUserTypeSeat != null) {
								PbUserTypeSeatLog pbUserTypeSeatLog = new PbUserTypeSeatLog();
								pbUserTypeSeatLog.setAdduser(userInfo.getUsername());
								pbUserTypeSeatLog.setTypeseatid(pbUserTypeSeat.getId());
								pbUserTypeSeatLogService.savePbUserTypeSeatLog(pbUserTypeSeatLog);

								//修改用户分区位置粉丝数
								pbUserTypeSeat.setFansnum(pbUserTypeSeat.getFansnum() + 1);
								pbUserTypeSeatService.updatePbUserTypeSeatFansnum(pbUserTypeSeat);
							}

							//添加关注
							saveFansattention(userInfo.getUsername(), um, FansAttentionType.TYPE_ATTENTION, following, followme);
							//添加粉丝
							saveFansattention(userInfo.getUsername(), um, FansAttentionType.TYPE_FANS, following, followme);

							addAttentionNum ++;
						} catch (WeiboException e) {
							logger.error("用户[" + userInfo.getNickname() + "]关注[" + um.getNickname() + "]异常:" + WeiboCons.getErrorMsg(e));
							//超过人数限制/你的关注人数已达上限/用户请求接口超过上限
							//if(e.getErrorCode() == 20521 || e.getErrorCode() == 20513 || e.getErrorCode() == 10024) {
							if(StringUtil.isEqualArr(e.getErrorCode(), 20521, 20513, 10024)) {
								errorWeiboMsg.append(WeiboCons.getErrorMsg(e));
								result = ERROR_WEIBO;
								break;
							}
							//添加粉丝[没有关注过该用户]
							else if(e.getErrorCode() != 20506) {
								following = "false";
							}
							else {
								//为互粉-添加关注
								saveFansattention(userInfo.getUsername(), um, FansAttentionType.TYPE_ATTENTION, following, followme);
							}
							saveFansattention(userInfo.getUsername(), um, FansAttentionType.TYPE_FANS, following, followme);
						}

					} catch (WeiboException e) {
						logger.error("用户[" + userInfo.getNickname() + "]添加粉丝[" + um.getNickname() + "]异常:" + WeiboCons.getErrorMsg(e));
						//用户不存在或token过期或access_token 无效
						//if(e.getErrorCode() == 20003 || e.getErrorCode() == 21327 || e.getErrorCode() == 21332) {
						if(StringUtil.isEqualArr(e.getErrorCode(), 20003, 21327, 21332)) {
							//修改token过期时间
							UserInfo ui = userInfoService.findByUserName(um.getUsername());
							ui.setAccessendtime(DateUtil.getTime());
							userInfoService.updateUserInfoTokentime(ui);
							//根据用户名删除可互粉用户信息
							userMpService.deleteByUsername(um.getUsername());
						}
						//超过人数限制/你的关注人数已达上限/用户请求接口超过上限
						//else if(e.getErrorCode() == 20521 || e.getErrorCode() == 20513 || e.getErrorCode() == 10024) {
						if(StringUtil.isEqualArr(e.getErrorCode(), 20521, 20513, 10024)) {
							//将该用户加入限制互粉名单
							FreezeUserUtil.addFreezeUser(um.getUsername());
						}
					}
				}

				if(result == null) {
					result = SUCCESS;
				}
				//发送互粉信息到微博
				if("true".equals(isSendWeibo) && addFansNum > 0) {
					String weiboContent = SystemCons.getWeiboMpContent(addFansNum);
					timelineService.updateStatus(weiboContent, userInfo.getToken());
				}
				//本次互粉后解冻的时间设置
				FreezeMpUserUtil.addMpFreezeUser(userInfo.getUsername(), userInfo.getFreezemptime());
			}
		} catch (WeiboException e) {
			logger.error(WeiboCons.getErrorMsg(e), e);
			result = ERROR_WEIBO;
			errorWeiboMsg.append(WeiboCons.getErrorMsg(e));
		} catch (Exception e) {
			logger.error("参与互粉异常!", e);
			result = ERROR;
		}
		ModelMap modelMap = new ModelMap();
		modelMap.put("result", result);
		modelMap.put("unFreezeMsg", unFreezeMsg);
		modelMap.put("addFansNum", addFansNum);
		modelMap.put("errorWeiboMsg", errorWeiboMsg);
		modelMap.put("joinMpMsg", "您成功添加了" + addFansNum + "个粉丝/成功关注了" + addAttentionNum + "个用户!");
		return modelMap;
	}

	/**
	 * 分区位置互粉
	 * @return
	 */
	@RequestMapping(value = "/fansattention/json/sureFaOutcast")
	@ResponseBody
	public ModelMap sureFaOutcast(HttpServletRequest request, Integer typeseatid, String uid) {
		String result = null;
		Integer errorWeiboCode = null;
		StringBuffer errorWeiboMsg = new StringBuffer();
		UserInfo userInfo = getSessionUser(request);
		if(userInfo.getIsopenmp().intValue() == 0) {
			result = ERROR_ISOPENMP;
		}
		else {
			//先同步信息
			//synchrologInfo(request, FansAttentionType.TYPE_FANS);

			UserInfo ui = null;
			String following = "true";
			String followme = "true";
			if(uid == null || "".equals(uid.trim())) {
				result = "uid_is_null";
			}
			else {
				try {
					ui = userInfoService.findByUserName(uid);
					//用户关注当前登录用户
					friendshipsService.createFriendshipsById(userInfo.getUsername(), ui.getToken());

					try {
						//当前登录用户关注用户
						friendshipsService.createFriendshipsById(ui.getUsername(), userInfo.getToken());
						//添加关注
						saveFansattention(userInfo.getUsername(), ui, FansAttentionType.TYPE_ATTENTION, following, followme);
						//添加粉丝
						saveFansattention(userInfo.getUsername(), ui, FansAttentionType.TYPE_FANS, following, followme);

						//添加位置互粉信息
						PbUserTypeSeatLog pbUserTypeSeatLog = new PbUserTypeSeatLog();
						pbUserTypeSeatLog.setAdduser(userInfo.getUsername());
						pbUserTypeSeatLog.setTypeseatid(typeseatid);
						pbUserTypeSeatLogService.savePbUserTypeSeatLog(pbUserTypeSeatLog);

						//修改用户分区位置粉丝数
						PbUserTypeSeat pbUserTypeSeat = pbUserTypeSeatService.findByIdPbUserTypeSeat(typeseatid);
						pbUserTypeSeat.setFansnum(pbUserTypeSeat.getFansnum() + 1);
						pbUserTypeSeatService.updatePbUserTypeSeatFansnum(pbUserTypeSeat);

					} catch (WeiboException e) {
						logger.error("用户[" + userInfo.getNickname() + "]和[" + ui.getNickname() + "]互粉异常:" + WeiboCons.getErrorMsg(e), e);
						//超过人数限制/你的关注人数已达上限/用户请求接口超过上限
						//if(e.getErrorCode() == 20521 || e.getErrorCode() == 20513 || e.getErrorCode() == 10024) {
						if(StringUtil.isEqualArr(e.getErrorCode(), 20521, 20513, 10024)) {
							errorWeiboMsg.append(WeiboCons.getErrorMsg(e));
							result = ERROR_WEIBO;
						}
						//添加粉丝[没有关注过该用户]
						else if(e.getErrorCode() != 20506) {
							following = "false";
						}
						else {
							//为互粉-添加关注
							saveFansattention(userInfo.getUsername(), ui, FansAttentionType.TYPE_ATTENTION, following, followme);
						}
						saveFansattention(userInfo.getUsername(), ui, FansAttentionType.TYPE_FANS, following, followme);
					}

					if(result == null) {
						result = SUCCESS;
					}
				} catch (WeiboException e) {
					logger.error("用户[" + userInfo.getNickname() + "]和[" + ui.getNickname() + "]互粉异常:" + WeiboCons.getErrorMsg(e));
					//用户不存在或token过期或access_token 无效
					//if(e.getErrorCode() == 20003 || e.getErrorCode() == 21327 || e.getErrorCode() == 21332) {
					if(StringUtil.isEqualArr(e.getErrorCode(), 20003, 21327, 21332)) {
						try {
							//修改token过期时间
							ui.setAccessendtime(DateUtil.getTime());
							userInfoService.updateUserInfoTokentime(ui);
							//修改位置为未被占领状态
							PbUserTypeSeat pbUserTypeSeat = new PbUserTypeSeat();
							pbUserTypeSeat.setUsername(ui.getUsername());
							pbUserTypeSeatService.updatePbUserTypeSeatUsernameToLog(pbUserTypeSeat);
							//根据用户名删除可互粉用户信息
							userMpService.deleteByUsername(ui.getUsername());
						} catch (Exception e1) {
							logger.error("处理用户不存在或token过期或access_token 无效的信息异常!", e);
						}
						result = "token_is_null";
					} else {
						result = ERROR_WEIBO;
					}
					errorWeiboCode = e.getErrorCode();
					errorWeiboMsg.append(WeiboCons.getErrorMsg(e));
				} catch (Exception e) {
					logger.error("互粉异常!", e);
					result = ERROR;
				}
			}
		}

		ModelMap modelMap = new ModelMap();
		modelMap.put("result", result);
		modelMap.put("errorWeiboCode", errorWeiboCode);
		modelMap.put("errorWeiboMsg", errorWeiboMsg);
		return modelMap;
	}

	/**
	 * 保存粉丝或关注信息
	 * @param username
	 * @param userInfo
	 * @param fansAttentionType
	 * @param following
	 * @param followme
	 * @throws Exception
	 */
	private void saveFansattention(String username, UserInfo userInfo, FansAttentionType fansAttentionType, String following, String followme) throws Exception {
		Fansattention fansattention = new Fansattention();
		fansattention.setUsername(username);
		fansattention.setFansattentionusername(userInfo.getUsername());
		fansattention.setNickname(userInfo.getNickname());
		fansattention.setFansnum(userInfo.getFansnum());
		fansattention.setAttentionnum(userInfo.getAttentionnum());
		fansattention.setWeibonum(userInfo.getWeibonum());
		fansattention.setGender(userInfo.getGender());
		fansattention.setImg(userInfo.getImg());
		fansattention.setType(fansAttentionType.getCode());
		fansattention.setFollowing(following);
		fansattention.setFollowme(followme);

		dealFansattention(fansattention);
	}

	/**
	 * 保存粉丝或关注信息
	 * @param username
	 * @param userMp
	 * @param fansAttentionType
	 * @param following
	 * @param followme
	 * @throws Exception
	 */
	private void saveFansattention(String username, UserMp userMp, FansAttentionType fansAttentionType, String following, String followme) throws Exception {
		Fansattention fansattention = new Fansattention();
		fansattention.setUsername(username);
		fansattention.setFansattentionusername(userMp.getUsername());
		fansattention.setNickname(userMp.getNickname());
		fansattention.setFansnum(userMp.getFansnum());
		fansattention.setAttentionnum(userMp.getAttentionnum());
		fansattention.setWeibonum(userMp.getWeibonum());
		fansattention.setGender(userMp.getGender());
		fansattention.setImg(userMp.getImg());
		fansattention.setType(fansAttentionType.getCode());
		fansattention.setFollowing(following);
		fansattention.setFollowme(followme);

		dealFansattention(fansattention);
	}

	private void dealFansattention(Fansattention fansattention) throws Exception {
		//判断数据库中是否存在
		if(fansAttentionService.findByUsernameFansnameType(fansattention) != null) {
			fansAttentionService.updateFansattention(fansattention);
		} else {
			//保存粉丝信息
			fansAttentionService.saveFansattention(fansattention);
		}
	}
}